﻿namespace Radius.NET.Core;

/// <summary>
/// 实体操作基服务
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public class BaseService<TEntity> : IDynamicApiController where TEntity : class, new()
{
    private readonly SqlSugarRepository<TEntity> _rep;

    public BaseService(SqlSugarRepository<TEntity> rep)
    {
        _rep = rep;
    }

    /// <summary>
    /// 获取实体详情
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [DisplayName("获取实体详情"),HttpPost]
    public virtual async Task<TEntity> GetDetail(long id)
    {
        return await _rep.GetByIdAsync(id);
    }

    /// <summary>
    /// 获取实体集合
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取实体集合"),HttpPost]
    public async Task<List<TEntity>> GetList(BasePageInput input)
    {
        return await _rep.AsQueryable().Where(ConvertParms(input.ConModels)).ToListAsync();
    }

    /// <summary>
    /// 获取实体分页
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Page"),HttpPost]
    [DisplayName("获取实体分页")]
    public async Task<SqlSugarPagedList<TEntity>> GetPage(BasePageInput input)
    {
        return await _rep.AsQueryable().Where(ConvertParms(input.ConModels)).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加实体
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    [DisplayName("增加实体")]
    public virtual async Task<bool> Add(TEntity entity)
    {
        return await _rep.InsertAsync(entity);
    }

    /// <summary>
    /// 更新实体
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    [DisplayName("更新实体")]
    public virtual async Task<bool> Update(TEntity entity)
    {
        return await _rep.UpdateAsync(entity);
    }

    /// <summary>
    /// 删除实体
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    [DisplayName("删除实体")]
    public virtual async Task<bool> Delete(long id)
    {
        return await _rep.DeleteByIdAsync(id);
    }

    #region 高级查询条件转换成SqlSugar
    /// <summary>
    /// 高级查询条件转换成SqlSugar
    /// </summary>
    /// <param name="customs"></param>
    /// <returns></returns>
    private List<IConditionalModel> ConvertParms(List<CustomConditionalModel> customs)
    {
        var colMos = new List<IConditionalModel>();
        if (customs is not null)
        {
            colMos.AddRange(customs.Adapt<List<ConditionalModel>>());
        }
        return colMos;
    }
    #endregion
}